<?php

/* empty stubs for now */
function cable_search_load($connector)
{
	return true;
}

function cable_search_unload($connector)
{
	return true;
}

function cable_search_open(&$connector)
{
	global $cable_search_plugin;
	
	$cable_search_plugin = array('fail'=>true);

	/* initialization */
	$cable_search_plugin[connector] = &$connector;
	$cable_search_plugin[author_names]		= array();
	$cable_search_plugin[timestamps]		= array();
	$cable_search_plugin[num]				= count($connector->data);
	$cable_search_plugin[next_timestamp]	= false; /* next result timestamp */
	$cable_search_plugin[prev_timestamp]	= false; /* previous results timestamp */
	$cable_search_plugin[entry_start_num]	= false;
	$cable_search_plugin[entry_end_num]		= false;
		
	/* retrieve plugin templates */
	/* need to add error checking on these at some point */
	$cable_search_plugin[result_template] = $connector->template->GetChild('CABLE-Result');
	if ($cable_search_plugin[result_template] === false)
		return 'Error retrieving search result template';
	
	$cable_search_plugin[field_template] = $connector->template->GetChild('CABLE-Field');
	if ($cable_search_plugin[field_template] === false)
		return 'Error retrieving search field template';
		
	$cable_search_plugin[category_template] = $cable_search_plugin[result_template]->GetChild('CABLE-Category');
	if ($cable_search_plugin[category_template] === false)
		return 'Error retrieving search result template';
	
	$cable_search_plugin[date_formats] = $connector->template->GetValue('CABLE-DateFormat',true);
	if (count($cable_search_plugin[date_formats]) == 0)
		$cable_search_plugin[date_formats] = array();
		
	$cable_search_plugin[search_fields] = $connector->template->GetValue('CABLE-SearchFields',true);
	if (count($cable_search_plugin[search_fields]) == 0)
		$cable_search_plugin[search_fields] = array();
		
	$cable_search_plugin[category_delimiter] = $connector->template->GetValue('CABLE-CategoryDelimiter');
	
	/* sort entries by descending timestamp */
	if ($connector->config['SearchSort'] != 'descending')
		krsort($connector->data);
	
	/* if no timestamp to start from has been given, get defaults */
	if ($_REQUEST['t'] == '')
	{
		if ($connector->config['SearchSort'] != 'descending')
			$start_timestamp = 0; 
		else
			$start_timestamp = time();/* entries later than the current time */
	}
	else
		$start_timestamp = urldecode($_REQUEST['t']);

	/* determine which timestamps of the entries we've been given we're to actually display */
	$counter = 0;
	foreach($connector->data as $timestamp => $data)
	{
		if ($connector->config['SearchSort'] == 'descending')
		{
			if (($timestamp <= $start_timestamp) && ($counter < $connector->config['ResultsPerPage']))
				$counter++;
			else
				$connector->data[$timestamp][delete] = true;
		}
		else
		{
			if (($timestamp >= $start_timestamp) && ($counter < $connector->config['ResultsPerPage']))
				$counter++;
			else
				$connector->data[$timestamp][delete] = true;
		}
	}
	
	/* restore original sorting method if necessary */
	if ($connector->config['SearchSort'] != 'descending')
		ksort($connector->data);

	/* find the previous and next result timestamps */
	/* now that sorting has been returned to normal, it's constructive to think of the results array in the following manner: */
	/*
		(entries previous to shown results)
		entry <timestamp> [delete]
		entry <timestamp> [delete]
		entry <timestamp> [delete]	< previous result
		entry <timestamp>			< displayed result
		entry <timestamp>			< displayed result
		entry <timestamp>			< displayed result
		entry <timestamp> [delete]	< next result
		entry <timestamp> [delete]
		entry <timestamp> [delete]
		entry <timestamp> [delete]
		(entries next to show results)
	*/
	
	$counter = 0;
	$is_prev = true;
	$previous_timestamps = array(); /* array to keep track of the previous timestamps */
	foreach($connector->data as $timestamp => $data)
	{
		if (($data[delete] !== true) && ($is_prev === true)) /* we'll no longer be previous to the shown results once we encounter a displayed entry */
		{
			$cable_search_plugin[entry_start_num] = $counter;
			$is_prev = false;
		}
		
		if (($is_prev === true) && ($data[delete])) /* keep popping the latest previous timestamp onto the front of the $previous_timestamps array */
			array_unshift($previous_timestamps,$timestamp);
			
		if (($data[delete]) && ($is_prev === false)) /* if we're encountering deleted entries, but is_prev is false, they must be the next entries */
		{
			if ($cable_search_plugin[next_timestamp] === false)
			{
				$cable_search_plugin[next_timestamp] = $timestamp;
				$cable_search_plugin[entry_end_num] = $counter;
			}
		}
		$counter++;
	}
	
	/* munge entry counters */
	if ($cable_search_plugin[entry_end_num] === false)
		$cable_search_plugin[entry_end_num] = $counter;
	$cable_search_plugin[entry_start_num]++;
	
	/* we need to "rewind" now the correct results to find a full page's worth of results */
	if (count($previous_timestamps) > 0)
		$cable_search_plugin[prev_timestamp] = $previous_timestamps[min(count($previous_timestamps) -1,$connector->config['ResultsPerPage'])];
	
	$cable_search_plugin[fail] = false;
	
	return true;
}

function cable_search(&$connector)
{	
	global $cable_search_plugin;
	
	/* sanity check */
	if ($cable_search_plugin[fail])
		return true;
	
	/* START ENTRY REPLACEMENTS */
	
	// straight (dumb) replacements
	foreach($connector->data as $field => $value)
	{
		if (is_bool($value))
			$cable_search_plugin[result_template]->SetBool('CABLE-Result.'.$field,$value);
		elseif(!is_array($value))
			$cable_search_plugin[result_template]->ReplaceInsert('CABLE-Result.'.$field,stripslashes(rawurldecode($value)));
	}

	// entry url replacements 
	if ($connector->config['EnableModRewrite'] > 0)
		$cable_search_plugin[result_template]->ReplaceInsert('CABLE-Result.url', $connector->config[SiteURL].$connector->data[timestamp]);
	else
		$cable_search_plugin[result_template]->ReplaceInsert('CABLE-Result.url', $connector->config[SiteURL].'entry.php?t='.$connector->data[timestamp]);

	// date replacements
	foreach($cable_search_plugin[date_formats] as $i => $f)
		$cable_search_plugin[result_template]->ReplaceInsert('CABLE-Result.date.'.$i,date($f,$connector->data[timestamp]));
	
	/* retrive author name information */
	if (($ret = CABLE_searchAuthor($connector->data[author],$connector->db_link)) !== true)
		return $ret;
	
	// author replacements
	foreach ($cable_search_plugin[author_names][$connector->data[author]] as $f => $v)
		$cable_search_plugin[result_template]->ReplaceInsert('CABLE-Result.author.'.$f,$v);

	// category replacements
	$counter = 0;
	foreach($connector->data[category] as $category)
	{
		$cable_search_plugin[category_template]->ReplaceInsert('CABLE-Category.name',$category);
		/* insert the delimiter between categories */
		if ($counter == 0)
			$cable_search_plugin[result_template]->AppendInsert('CABLE-Result.categories',$cable_search_plugin[category_template]->template);
		else
			$cable_search_plugin[result_template]->AppendInsert('CABLE-Result.categories',$cable_search_plugin[category_delimiter].$cable_search_plugin[category_template]->template);
		
		$cable_search_plugin[category_template]->Reset();
		$counter++;
	}

	/* save the current template information to the connector template */
	$connector->template->AppendInsert('CABLE-Results',$cable_search_plugin[result_template]->template);
	$cable_search_plugin[result_template]->Reset();
	
	return true;
}

function cable_search_close(&$connector)
{
	global $cable_search_plugin;
	
	/* sanity check */
	if ($cable_search_plugin[fail])
		return true;
	
	/* explain errors, if necessary */
	if (strlen(urldecode($_REQUEST['s'])) < 4)
	{
		$connector->template->SetBool('CABLE-Error',true);
		$connector->template->SetBool('CABLE-Error.text','Search value must be at least four characters long.');
	}
	
	/* do search information replacements */
	$connector->template->ReplaceInsert('CABLE-Search.string',urldecode($_REQUEST['s']));
	$connector->template->ReplaceInsert('CABLE-Search.field',urldecode($_REQUEST['f']));
	
	/* do field menu */
	foreach($cable_search_plugin[search_fields] as $pair)
	{
		list($value,$name) = explode(',',$pair);
		
		$cable_search_plugin[field_template]->Reset();
		$cable_search_plugin[field_template]->ReplaceInsert('CABLE-Field.name',$name);
		$cable_search_plugin[field_template]->ReplaceInsert('CABLE-Field.value',$value);
		$cable_search_plugin[field_template]->SetBool('CABLE-Field.selected',($value == urldecode($_REQUEST['f'])));
		
		$connector->template->AppendInsert('CABLE-Fields',$cable_search_plugin[field_template]->template);
	}
	
	/* do results statistics */
	$connector->template->ReplaceInsert('CABLE-Results.num',$cable_search_plugin[num]);
	if ((count($connector->data) > 0) && ($_REQUEST['s'] != ''))
		$connector->template->SetBool('CABLE-Results',true);
	elseif($_REQUEST['s'] != '')
		$connector->template->SetBool('CABLE-Results',false);
	$connector->template->ReplaceInsert('CABLE-Results.start',$cable_search_plugin[entry_start_num]);
	$connector->template->ReplaceInsert('CABLE-Results.end',$cable_search_plugin[entry_end_num]);

	/* do top level replacements */
	$connector->template->ReplaceInsert('CABLE-Site.name',$connector->config[SiteName]);
	$connector->template->ReplaceInsert('CABLE-Base.url',$connector->config[SiteURL]);
	$connector->template->ReplaceInsert('CABLE-Files.url',$connector->config[SiteURL].'files/'.$connector->config[ThemeName].'/');
	$connector->template->ReplaceInsert('CABLE-CSS.url',$connector->config[SiteURL].'css/'.$connector->config[ThemeName].'/');
	
	/* do navigation */
	$nav_url = $connector->config[SiteURL].'search.php?s='.$_REQUEST['s'].'&amp;f='.$_REQUEST['f'].'&amp;t=';
	if ($cable_search_plugin[prev_timestamp])
	{
		$connector->template->SetBool('CABLE-Pages.previous',true);
		$connector->template->ReplaceInsert('CABLE-Nav.prev.url',$nav_url.$cable_search_plugin[prev_timestamp]);
	}
	else
		$connector->template->SetBool('CABLE-Pages.previous',false);

	if ($cable_search_plugin[next_timestamp])
	{
		$connector->template->SetBool('CABLE-Pages.next',true);
		$connector->template->ReplaceInsert('CABLE-Nav.next.url',$nav_url.$cable_search_plugin[next_timestamp]);
	}
	else
		$connector->template->SetBool('CABLE-Pages.next',false);

	/* set user info */
	$connector->template->SetBool('CABLE-User.loggedin',$connector->user->logged_in);
	$connector->template->SetBool('CABLE-User.isadmin',$connector->user->is_admin);
	$permissible = array('username','fullname','firstname','lastname');
	foreach($connector->user->values as $f => $v)
		if (in_array($f,$permissible))
			$connector->template->ReplaceInsert('CABLE-User.'.$f,$v);
	
	/* free up memory */
	unset($cable_search_plugin);

	return true;
}

function CABLE_searchAuthor($a,$db_link)
{
	global $cable_search_plugin;
	
	/* retrieve author information from database and save into array */
	if (!$cable_search_plugin[author_names][$a])
	{
		$table = "cable_".$cable_search_plugin[connector]->config['TablePrefix']."_users";
		$query = "SELECT username,fullname FROM $table WHERE (username = '".$a."') LIMIT 1";
		if ((($result = mysql_query($query,$db_link)) !== false) && (mysql_num_rows($result) == 1))
		{
			$cable_search_plugin[author_names][$a] = mysql_fetch_assoc($result);
			list(
				$cable_search_plugin[author_names][$a]['firstname'],
				$cable_search_plugin[author_names][$a]['lastname']
			) = explode(' ',$cable_search_plugin[author_names][$a]['fullname']);
		}
		else /* something went to shit */
			return 'Error accessing author table.';
	}
	
	return true;
}

?>